const express = require("express");
const router = express.Router();
const path = require('path');
const fs = require('fs');
const pool = require("../pool.js");
const utils = require("../utils/index.js");
const moment = require("moment-timezone");
const multer = require("multer");
const axios = require("axios");
const CryptoJS = require("crypto-js");
const config = require("../config");
const { content } = require("googleapis/build/src/apis/content/index.js");
const apiKey = process.env.OPENAI_API_KEY;
// 配置 multer 的存储设置
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        // 设置文件上传目录
        cb(null, "/home/wwwroot/default/beautyImages");
    },
    filename: function (req, file, cb) {
        // 生成文件名
        cb(null, Date.now() + "-" + file.originalname);
    },
});

const upload = multer({ storage: storage });

// 创建文件上传的 POST 接口
router.post("/upload", upload.single("file"), (req, res) => {
    const file = req.file;
    const { pk } = req.body;
    if (!file) {
        return res.status(400).send("请上传一个文件。");
    }
    let fileUrl = ''
    //安卓qrcode 放ins2服务器

    fileUrl = `https://insdoss.freeapptools.com/beautyImages/${file.filename}`;



    // 返回文件存储地址
    res.send({
        code: 0,
        message: "success",
        fileUrl: fileUrl,
    });
});

//imageToProduct
router.post("/getimageToProductConfig", async (req, res) => {
    const { version } = req.body
    let sql = `SELECT * FROM ai_debug WHERE version = ?`;
    let result = await mysqlQuery(sql, [version]);
    res.send({ code: 0, data: result[0] })
});
router.post("/updateimageToProductConfig", async (req, res) => {
    let { name } = await utils.getUserInfo(req, res);
    const { prompt_test, temperature_test, max_tokens_test, top_p_test, frequency_penalty_test, presence_penalty_test, model_test, id } = req.body
    const sql = `
            UPDATE ai_debug
            SET 
                prompt_test = ?, 
                temperature_test = ?, 
                max_tokens_test = ?, 
                top_p_test = ?, 
                frequency_penalty_test = ?, 
                presence_penalty_test = ?, 
                model_test = ?, 
                update_by = ?,
                update_date = ?
            WHERE id = ?
        `;
    let result = await mysqlQuery(sql, [prompt_test, temperature_test, max_tokens_test, top_p_test, frequency_penalty_test, presence_penalty_test, model_test, name, utils.formatDate(new Date()), id])
    res.send({ code: 0, data: result[0] })
});
router.post("/updateimageToProductConfigHandel", async (req, res) => {
    let { name } = await utils.getUserInfo(req, res);
    const { prompt_test, temperature_test, max_tokens_test, top_p_test, frequency_penalty_test, presence_penalty_test, model_test, id } = req.body
    const sql = `
            UPDATE ai_debug
            SET 
                prompt_release = ?,
                temperature = ?,
                max_tokens = ?,
                top_p = ?,
                frequency_penalty = ?,
                presence_penalty = ?,
                model = ?,
                update_by = ?,
                update_date = ?
            WHERE id = ?
        `;
    let result = await mysqlQuery(sql, [prompt_test, temperature_test, max_tokens_test, top_p_test, frequency_penalty_test, presence_penalty_test, model_test, name, utils.formatDate(new Date()), id])
    res.send({ code: 0, data: result[0] })
});
router.post('/getimageToProductVersionList', async (req, res) => {
    try {
        let sql = `SELECT version FROM ai_debug`;
        let result = await mysqlQuery(sql, []);
        const formattedResult = result.map(row => ({
            id: row.version,
            name: row.version
        }));

        res.send({
            data: formattedResult
        });
    } catch (error) {
        console.error("Error fetching versions:", error);
        res.status(500).json({ error: "Internal server error" });
    }
});

router.post('/addimageToProductVersion', async (req, res) => {
    const { version } = req.body;
    try {
        // 检查表中是否已经有相同的版本
        const existingVersion = await mysqlQuery('SELECT 1 FROM ai_debug WHERE version = ?', [version]);
        if (existingVersion.length > 0) {
            return res.send({ code: 1, msg: '版本已存在' });
        }
        // 获取表中最后一条记录
        const lastRecord = await mysqlQuery('SELECT * FROM ai_debug ORDER BY id DESC LIMIT 1', []);

        if (lastRecord.length === 0) {
            return res.send({ code: 1, msg: '没有可复制的记录' });
        }
        // 从最后一条记录中获取值，并修改版本
        let newRecord = { ...lastRecord[0], version };

        delete newRecord.id;
        newRecord.id = utils.createId();
        // 插入新记录
        const insertQuery = 'INSERT INTO ai_debug SET ?';
        await mysqlQuery(insertQuery, [newRecord]);

        res.send({ code: 0, msg: 'success' })

    } catch (error) {
        console.error(error);
        res.status(500).json({ error: '数据库操作失败，请稍后重试' });
    }
})
router.post("/imageToProduct-analysis", async (req, res) => {

    let parseData = req.body.query;
    let content = JSON.parse(decrypt(parseData, config.cryptoKey, config.cryptoIv));
    const chinaTime = new Date();
    console.log(content, 'content' + chinaTime.toLocaleString())
    if (content.code != 'OZqcJQLBUyevTh') return
    const { imageUrl, version, pk } = content


    let sql = `SELECT * FROM ai_debug WHERE version = ?`;
    let params = [version || '1.0.12']; // Use the specified version or the default version
    let result = await mysqlQuery(sql, params);
    // If there is no result for the specified version, query all versions and get the latest one
    if (result.length === 0 && version) {
        sql = `
         SELECT * FROM ai_debug
        ORDER BY id DESC
        LIMIT 1
    `;
        result = await mysqlQuery(sql);
    }






    const { prompt_release, temperature, max_tokens, top_p, frequency_penalty, presence_penalty, model } = result[0]
    try {
        // 将 imageUrl 转换为 Base64
        // const imageResponse = await axios.get(imageUrl, { responseType: 'arraybuffer' });
        // const imageBase64 = Buffer.from(imageResponse.data, 'binary').toString('base64');
        // console.log(imageBase64)
        const response = await axios.post(
            'https://api.openai.com/v1/chat/completions',
            {
                model: model,
                messages: [
                    {
                        role: 'system',
                        content: [
                            {
                                type: 'text',
                                text: prompt_release
                            }
                        ]
                    },
                    {
                        role: 'user',
                        content: [
                            {
                                type: 'image_url',
                                image_url: {
                                    // url: 'https://www.the-sun.com/wp-content/uploads/sites/6/2020/05/stassi.jpeg'
                                    url: imageUrl
                                }
                            }
                        ]
                    }
                ],
                response_format: {
                    type: 'text'
                },
                temperature: Number(temperature),
                max_tokens: Number(max_tokens),
                top_p: Number(top_p),
                frequency_penalty: Number(frequency_penalty),
                presence_penalty: Number(presence_penalty)
            },
            {
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer   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`
                }
            }
        );
        console.log(imageUrl, '结果' + chinaTime.toLocaleString())

        // 获取 token 消耗信息
        const { usage } = response.data;
        const { prompt_tokens, completion_tokens, total_tokens } = usage;
        // 存储 token 消耗到数据库
        const date = utils.formatDate1(new Date());
        let id = utils.createId();
        // 需要插入的内容
        let message = null;
        let url = imageUrl

        // 如果 completion_tokens 小于 200，则存储 message
        // if (completion_tokens < 200) {
        //     message = JSON.stringify(response.data.choices[0].message);

        // }
        if (response.data.choices[0].message) {
            message = JSON.stringify(response.data.choices[0].message);

        }
        const messageData = JSON.parse(message);
        const parsedData = extractAndParseJson(messageData.content);
        let code = parsedData.error_info.error_code
        const insertSql = `INSERT INTO ai_tokens (id,pk,code,version,date,type, prompt_tokens, completion_tokens, total_tokens,message,url,model,create_date,update_date) VALUES (?,?,?,?, ?,?,?, ?,?,?,?, ?, ?,?)`;
        await mysqlQuery(insertSql, [id, pk, code, version, date, 'imageToProduct', prompt_tokens, completion_tokens, total_tokens, message, url, model, utils.formatDate(new Date()), utils.formatDate(new Date())]);
        let data = encrypt(
            JSON.stringify(response.data.choices[0].message),
            config.cryptoKey,
            config.cryptoIv
        );
        res.send({
            code: 0,
            msg: 'success',
            data: data
        })
    } catch (error) {
        console.error('Error making API request:', error.response ? error.response.data : error.message);
        res.send({
            code: 1,
            msg: error.response ? error.response.data : error.message,
        })
    }

});
async function mysqlQuery(sql, arr) {

    return new Promise((resolve, reject) => {
        pool.query(sql, arr, (error, results, fields) => {

            if (error) {
                console.log(error)
                return reject(error);
            }
            resolve(results);
        });
    });
}
module.exports = router;
